package edu.hrbeu.controller;

import edu.hrbeu.entity.Book;
import edu.hrbeu.entity.Category;
import edu.hrbeu.mapper.CategoryMapper;
import edu.hrbeu.service.BookService;
import edu.hrbeu.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author wzq
 * @create 2022-01-06-10:32
 */
@Controller
public class BookController {

    @Autowired
    BookService bookService;

    @Autowired
    CategoryService categoryService;

    //vue
    @RequestMapping("/book/list_vue")
    public void list_vue() {
    }

    @RequestMapping("/book/category/list")
    @ResponseBody
    public List<Category> categoryList() {
        return categoryService.list();
    }

    //以json的形式返回列表
    @RequestMapping("/book/list2")
    @ResponseBody
    public List<Book> BookList1(Book book) {
        return bookService.search(book);
    }

    @PostMapping(value = "/book/list2", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public List<Book> BookList2(@RequestBody Book book) {
        return bookService.search(book);
    }

    //thymeleaf
    @GetMapping("/book/add")
    public void add(Model model) {
        model.addAttribute("categories", categoryService.list());
    }

    @PostMapping("/book/add")
    public String add(Book book) {
        bookService.save(book);
        return "redirect:/book/list";
    }

    @RequestMapping("/book/list")
    public void list(Model model, Book book) {
        model.addAttribute("bookList", bookService.search(book));
        System.out.println(book.toString());
        model.addAttribute("categories", categoryService.list());
        model.addAttribute("bookName", book.getName());
        model.addAttribute("categoryId", book.getCategory() != null ? book.getCategory().getId() : null);
//        return "book/list";
    }

    @PostMapping(path = "/book/add2", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String add2(@RequestBody Book book) {
        return bookService.save(book) ? "success" : "fail";
    }
}
